<?php
/**
 * @param $ip
 * @return string
 * 通过ip获取地址
 */
function getIpAddress($ip){
    if (empty($ip) || !isset($ip)){
        return '';
    }
    $host = "http://iploc.market.alicloudapi.com";
    $path = "/v3/ip";
    $method = "GET";
    $appcode = "e6bdec1ee15c497fafb30cf817ba72bf";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    $querys = "ip=".$ip;
    $bodys = "";
    $url = $host . $path . "?" . $querys;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    if (1 == strpos("$".$host, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $data = curl_exec($curl);
    $start = strpos($data,'{');
    $end   = strpos($data,'}');
    $address = substr($data,$start,$end);
    $address = json_decode($address,true);
    if ($address['status'] == 1){
        return $address['province'].' '.$address['city'];
    }else{
        return '';
    }
}

/**
 * 获取访问者真实IP
 */
if(!function_exists('get_real_ip')){
    function get_real_ip(){
        $ip = FALSE;
        //客户端IP 或 NONE
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
        if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if($ip){
                array_unshift($ips, $ip);
                $ip = FALSE;
            }
            for($i = 0; $i < count($ips); $i++){
                if(!eregi("^(10│172.16│192.168).", $ips[$i])){
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        //客户端IP 或 (最后一个)代理服务器 IP
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }
}